import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../contants/constant.dart';

class DbUtils with ChangeNotifier {
  /**
   * 保存当前新增的路径 key value
   */
  Future<void> saveResListPath(String key, String value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var resMapAll = await loadResListPath();
    debugPrint("resMapAll:${resMapAll}");
    dynamic json;
    if (resMapAll != null && resMapAll.isNotEmpty) {
      json = jsonDecode(resMapAll);
      debugPrint("json:${json}");
    } else {
      json = {};
    }
    if (!json.containsKey(key)) {
      json[key] = value;
    } else {
      debugPrint("路径已存在");
    }
    await prefs.setString("resList", jsonEncode(json));
  }

  /**
   * 获取路径列表
   */
  Future<String?> loadResListPath() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? data = prefs.getString("resList");
    debugPrint("loadResListPath:${data}");
    return Future(() => data);
  }

  /**
   * 删除路径列表
   */
  Future<void> delResListPath() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("resList", "");
  }

  /**
   * 保存当前多语言语种配置
   */
  Future<void> saveTranslateConfig(dynamic config) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    debugPrint("TranslateConfig:${config}");
    dynamic json;
    if (config != null && config.isNotEmpty) {
      json = config;
    } else {
      json = "";
    }
    await prefs.setString("TranslateConfig", jsonEncode(json));
  }

  /**
   * 获取多语言配置列表
   */
  Future<List> loadTranslateConfig() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? data = prefs.getString("TranslateConfig");
    debugPrint("loadResListPath:${data}");
    if (data == null || data.isEmpty || data == "[]") {
      // 将列表中的每个对象转换为 Map
      List mapList =
          Constant.translate_list.map((bean) => bean.toJson()).toList();
      // 使用 jsonEncode 方法将 Map 列表转换为 JSON 字符串
      return Future(() => mapList);
    } else {
      List list = jsonDecode(data);
      return Future(() => list);
    }
  }
}
